package com.yupi.springbootinit.controller;

import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.DepartmentTaskStatsVO;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.service.WorkflowTaskService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/department")
@Slf4j
public class DepartmentStatsController {

    @Resource
    private WorkflowTaskService workflowTaskService;

    @Resource
    private UserService userService;

    /**
     * 部门任务统计（仅允许查询自己所在部门）
     */
    @GetMapping("/{departmentId}/task-stats")
    public BaseResponse<DepartmentTaskStatsVO> getDepartmentTaskStats(@PathVariable Long departmentId, HttpServletRequest request) {
        if (departmentId == null || departmentId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null || loginUser.getDepartmentId() == null || !departmentId.equals(loginUser.getDepartmentId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该部门统计");
        }
        DepartmentTaskStatsVO vo = workflowTaskService.getDepartmentTaskStats(departmentId);
        return ResultUtils.success(vo);
    }
}